import 'package:demo/tools/tools_perms.dart';
import 'package:demo/tools/tools_scan.dart';
import 'package:demo/component/component_popup.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:demo/config/app_fonts.dart';
import 'package:demo/views/msg/msg_index_controller.dart';
import 'package:demo/tools/tools_enum.dart';
import 'package:demo/tools/tools_route.dart';
import 'package:demo/tools/tools_sqlite.dart';
import 'package:demo/component/component_common.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

// 消息页面
class MsgIndexView extends GetView<MsgIndexController> {
  const MsgIndexView({super.key});

  @override
  Widget build(BuildContext context) {
    Get.lazyPut<MsgIndexController>(() => MsgIndexController());
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onPanDown: (details) {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          title: const Text('消息'),
          actions: [
            ComponentPopup(
              dataList: [
                PopupModel(
                  '发起群聊',
                  const Icon(
                    AppFonts.e615,
                    color: Colors.green,
                    size: 20,
                  ),
                  onTap: () {
                    // 提醒
                    EasyLoading.showToast('敬请期待');
                  },
                ),
                PopupModel(
                  '扫一扫',
                  const Icon(
                    AppFonts.e60c,
                    color: Colors.orange,
                    size: 20,
                  ),
                  onTap: () async {
                    bool result = await ToolsPerms.camera();
                    if (!result) {
                      return;
                    }
                    ToolsScan.scan();
                  },
                ),
              ],
            ),
          ],
        ),
        body: GetBuilder<MsgIndexController>(builder: (builder) {
          List dataList = builder.refreshList;
          if (dataList.isEmpty) {
            return ComponentCommon.none();
          }
          return Column(
            children: [
              _buildSearch(),
              Flexible(
                child: SlidableAutoCloseBehavior(
                  child: ListView.separated(
                    itemCount: dataList.length,
                    separatorBuilder: (context, index) {
                      return ComponentCommon.divider();
                    },
                    itemBuilder: (context, index) {
                      ChatMsg chatMsg = dataList[dataList.length - index - 1];
                      return _slidable(chatMsg);
                    },
                  ),
                ),
              ),
            ],
          );
        }),
      ),
    );
  }

  // 滑动组件
  _slidable(ChatMsg chatMsg) {
    String chatId = chatMsg.chatId;
    return Slidable(
      key: ValueKey(chatId),
      endActionPane: ActionPane(
        motion: const BehindMotion(),
        extentRatio: 0.6,
        children: [
          SlidableAction(
            onPressed: (context) {
              controller.setShow(chatId);
            },
            backgroundColor: Colors.orange,
            foregroundColor: Colors.white,
            label: '不显示',
          ),
          SlidableAction(
            onPressed: (context) {
              controller.setDelete(chatId, chatMsg.chatTalk);
            },
            backgroundColor: Colors.red,
            foregroundColor: Colors.white,
            label: '删除',
          ),
        ],
      ),
      child: Column(
        children: [
          _buildItem(chatMsg),
          ComponentCommon.divider(),
        ],
      ),
    );
  }

  // 搜索框
  _buildSearch() {
    return TDSearchBar(
      placeHolder: '请输内容',
      onTextChanged: (values) {},
    );
  }

  // 消息
  _buildItem(ChatMsg chatMsg) {
    return Container(
      color: chatMsg.top ? Colors.grey[100] : Colors.white,
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16),
        leading: ComponentCommon.showAvatar(
          chatMsg.portrait,
        ),
        title: Text(
          chatMsg.nickname,
          style: const TextStyle(color: Colors.black),
          overflow: TextOverflow.ellipsis,
        ),
        subtitle: Padding(
          padding: const EdgeInsets.only(top: 6),
          child: _formatContent(chatMsg),
        ),
        trailing: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            ComponentCommon.timeFormat(
              chatMsg.createTime,
              chatMsg.msgId.isNotEmpty,
            ),
            if (chatMsg.disturb)
              const Padding(
                padding: EdgeInsets.only(top: 10),
                child: Icon(
                  AppFonts.ec83,
                  size: 18,
                  color: Color(0xFFa9a9a9),
                ),
              ),
          ],
        ),
        onTap: () {
          ToolsRoute().chatPage(
            chatId: chatMsg.chatId,
            nickname: chatMsg.nickname,
            portrait: chatMsg.portrait,
            chatTalk: chatMsg.chatTalk,
          );
        },
      ),
    );
  }

  _formatContent(ChatMsg chatMsg) {
    String content;
    MsgType msgType = chatMsg.msgType;
    // 内容
    switch (msgType) {
      case MsgType.text:
      case MsgType.tips:
        content = chatMsg.content['data'];
        break;
      default:
        content = msgType.label;
        break;
    }
    return Text(
      content,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(
        fontSize: 12,
        color: MsgType.none == msgType ? Colors.red : const Color(0xFFa9a9a9),
      ),
      maxLines: 1,
    );
  }
}
